<?php

namespace app\support;

use app\popo\model\Employee;
use app\popo\model\User;
use support\Log;
use think\helper\Arr;
use Tinywan\Jwt\JwtToken;

class JwtHelper
{
    /**
     * access_token.
     */
    private const ACCESS_TOKEN = 1;

    /**
     * refresh_token.
     */
    private const REFRESH_TOKEN = 2;

    /** WEB Client. */
    public const TOKEN_CLIENT_WEB = 'WEB';

    /** Mobile Client. */
    public const TOKEN_CLIENT_MOBILE = 'MOBILE';
    public static function generate(Employee $employee)
    {
        $user = array(
            "id" => $employee->id,
            "username" => $employee->username,
        );

        return JwtToken::generateToken($user);
    }

    public static function getEmployee(): Employee
    {
        $token = request()->cookie("token");
        if (!$token) {
            return new Employee();
        }
        $jwtInfo = JwtHelper::verify($token);
        $userId = Arr::get($jwtInfo, "extend.id");
        if (empty($userId)) {
            return new Employee();
        }

        return Employee::find($userId);
    }

    public static function getUser(): User
    {
        $token = request()->header("authentication");
        if (!$token) {
            return new User();
        }
        $jwtInfo = JwtHelper::verify($token);
        $userId = Arr::get($jwtInfo, "extend.id");
        if (empty($userId)) {
            return new User();
        }

        return User::find($userId);
    }

    public static function verify(string $token): array
    {
        return JwtToken::verify(self::ACCESS_TOKEN, $token);
    }

    public function test(): \support\Response
    {
        return json("依赖注入了");
    }

    public static function generateWx(User $user): array
    {
        return JwtToken::generateToken(array(
            "id" => $user->id,
            "username" => $user->name,
            "client" => JwtToken::TOKEN_CLIENT_MOBILE,
        ));
    }
}